<template>
  <el-dialog v-model="open" width="95%" :style="{ position: 'absolute', top: '30px', left: '50px', margin: '0' }"  :draggable="true">
    <div class="image-container">
      <div class="image-item" v-for="(src, index) in data.srcList" :key="src.src">
        <img :src="src.src" alt="image" @click="openEditDialog(src)" />
        <el-popover
            placement="top-start"
            trigger="hover"
            :popper-style="popoverSelf"
            :disabled="false"
            :visible="src.showPopover"
        >
          <template #reference>
<!--            <div v-show="src.mode === 'view'" v-for="(test, index) in src.item" :key="test.describe"  style="display: flex; gap: 5px;"  @click="turnEditMode(src)">-->
<!--              <TagTest :text='test.describe' :total-color="test.color"  :marginLeft="letDistance" fontSize="20px"  >-->
<!--              </TagTest>-->
<!--            </div>-->
            <div  style="display: flex; gap: 5px; overflow: hidden" @click="turnEditMode(src)"  v-if="src.mode === 'view'"
                  @mouseleave="closePopover(src)"  @mouseenter="openPopover(src)" >
              <TempTest :item="src.item"></TempTest>
            </div>

            <div   v-if="src.mode === 'edit'">
              <TagSelect
                :model-value="remoteSelectTest.modelValue"
                :placeholder="remoteSelectTest.placeholder"
                :fetch-options="remoteSelectTest.fetchOptions"
                :api="remoteSelectTest.api"
                :data="src"
                @update:modelValue="sureChange"
                :field-mappings="remoteSelectTest.fieldMappings"
                @focusout="closePopover(src)"
                @focus="openPopover(src)"
                @modelEntry="newOneItem"
                @fatherMothed="showPopover"
              ></TagSelect>
            </div>
          </template>

          <template #default>
            <div style="display: flex; gap: 5px;">
              <div v-for="(test, index) in src.item" :key="test.describe">
                <TagTest :text='test.describe' :total-color="test.color" :marginLeft="letDistance"
                         fontSize="20px">
                </TagTest>
              </div>
            </div>
          </template>

        </el-popover>

      </div>
      <MulitFileUpload ref="uploadRef" @updateUrlData="getUrlList" class="image-item" :master-id="itemTest.id" :height="itemTest.height" ></MulitFileUpload>
      <TagEidtDialog ref="editDialogRef" ></TagEidtDialog>

    </div>

  </el-dialog>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, toRef, toRefs, watch} from "vue";
import TagTest from "@/views/novel/tag/components/Children/tagTest.vue";
import TagEidtDialog from "@/views/club/life/Compent/TagEidtDialog.vue";
import TagSelect from "@/views/club/life/Compent/TagSelect.vue";
import TempTest from "@/views/club/life/Compent/TempTest.vue";
import MulitFileUpload from "@/views/novel/character/components/MulitFileUpload.vue";
import type {DetailModePictureForm} from "@/api/types/detailmodel/detailModePicture";
import {remoteTagApi} from "@/api/modules/novel/chararterTag";
import {useDictOptions} from "@/hooks/useDictOptions";
import {changeOneLifePictureApi, createOneLifeDayApi} from "@/api/modules/life/lifeDay";
import type {LifeDayForm} from "@/api/types/life/lifeDay";
import {ElMessage} from "element-plus";

let open = ref(false);
let letDistance = ref('0px');
let uploadRef = ref();
let editDialogRef = ref(false);
let mode = ref("view");
let selectingTarget = ref()
const colorArr = useDictOptions('tagColor');

let props =defineProps({
  srcList: Array
})

//不对不对真用父组件的内存块了，勾八规则我跟你爆了
//不用toRef，自动直接转移【不是复制值】
let data = reactive({
  id: Number,
  srcList: props.srcList ?? []
})

let emit = defineEmits(['emitRefreshList'])


let itemTest = {
  id: 22,
  describe:'test',
  color: 'rgba(255, 148, 2, 0.1)',
  remark:'test',
  left: '0px',
  itemSize: 2,
  height: 222
}

let remoteSelectTest = reactive({
  modelValue: '',
  placeholder: '输入标签名',
  fetchOptions: remoteTagApi,
  api: (query: any) => ({ keyword: query }),
  fieldMappings: {
    key: 'id',
    label: 'tagName',
    value: 'id'
  }
})

let sureChange = (newValue :any, dataFrom :any, option: any)=>{
    let target =data.srcList.find(item=>item.src === dataFrom.src)
    if (target){
      target.showPopover =true
      let item = {
          id: option.id,
          color:option.color,
          colorName:option.colorName,
          describe:option.tagName
      }
      target.item.push(item)
    }
}

let newOneItem = (keyword:any, src : any)=>{
  let total = colorArr.value.length; // Assuming colorArr is an array
  let randomIndex = Math.floor(Math.random() * total); // Generate random index
  let targetColor = colorArr.value[randomIndex]; // Get the color at the random index
  console.log('asdfwefsad234235', targetColor);
  let item = {
    color:targetColor.detailValue,
    colorName:targetColor.codeName,
    describe:keyword
  }
  console.log('JSON.parse(JSON.stringify(item))',JSON.parse(JSON.stringify(item)));
  src.item.push(JSON.parse(JSON.stringify(item)));

}

let srcList = ref([
  {src:'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',item: [itemTest,itemTest],showPopover:false,mode:'view'},
  {src:'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',item: [itemTest,itemTest],showPopover:false,mode:'view'},
  {src:'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg',item: [itemTest,itemTest],showPopover:false,mode:'view'},
]);


let popoverSelf ={
  zIndex: 9999,
  backgroundColor: 'black',
  width: 'auto',
  whiteSpace: 'nowrap'
}


let turnEditMode = (src :any) => {
  console.log('srcccccccc',src)
  if (selectingTarget.value){
    selectingTarget.value.mode ='view'
  }
  selectingTarget = toRef(src)

  if(src.mode === 'view'){
    src.mode ='edit';
    return
  }

};

let openEditDialog = (src: any) => {
  editDialogRef.value.openLifeEditDialog(src.src,src.item,data.srcList)
};


let showPopover = (dataFrom: any) => {
  let target =data.srcList.find(item=>item.src === dataFrom.src)
  if (target){
    target.showPopover =true
  }
};

let openLifeViewDialog = (id: any) => {
  if (id){
    data.id = id
  }
  open.value = true;
  colseTab()
};

let popoverShow = (src: any) => {
    return !src.showPopover && src.item.length < 4
};


let closePopover = (src: any) => {
  src.showPopover = false;
};


let openPopover = (src: any) => {
  src.showPopover = true;
};


let colseTab = ()=>{
  const tabBox = document.querySelector('.tabs-box');
  if (tabBox) {
    tabBox.style.zIndex = '-1';
  } else {
    console.log('未找到 .tabs-box 元素');
  }
}

let openTab = () => {
  const tabBox = document.querySelector('.tabs-box');
  if (tabBox) {
    tabBox.style.removeProperty('z-index');
  } else {
    console.log('未找到 .tabs-box 元素');
  }
};

let getUrlList = (res: any)=>{
  let newSrcList = []
  let pictures = res?.data?.map((itemIn:any)=>{
    let form :DetailModePictureForm ={}
    form.belongId = 2
    form.pictureId =itemIn?.url
    form.isAvatar = '0'
    newSrcList.push({src:itemIn?.url,item:[],showPopover:true,mode:'edit'})
    return form
  })
  console.log('asdfasdfasdf',props.srcList)
  console.log('asdfasdfasd2222f',data.srcList)
  data.srcList.push(...newSrcList)
}



watch(() => open.value, (newValue) => {
    if (!newValue){
      data.srcList.forEach((s)=>{
        s.mode = 'view'
      })

      //为修改时上传图片
      //不明原因用data.id会失效
      // 用isNaN才行
      if (data.id && !isNaN(data.id)) {
        let changeTarget : LifeDayForm= {
          srcList : data.srcList,
          id: data.id
        }
        changeOneLifePictureApi(changeTarget).then((res)=>{
          ElMessage.success('保存成功')
          emit('emitRefreshList')
        }).catch(()=>{
          console.log('触发异常了----')
          //异常则抛弃图片
          emit('emitRefreshList')
        })
      }

      openTab()
    }
})

//不明原因子更新能传父，父更新不能传子
watch(() => data.srcList, (newValue) => {
  console.log('不明原因子更新能传父，父更新不能传子',newValue)
  console.log('父组件触发了更新667677657657',newValue)
})



defineExpose({openLifeViewDialog ,data})

</script>

<style scoped lang="scss">

:deep(.el-input-group__append){
  padding: 0
}

.image-container {
  display: grid;
  grid-template-columns: repeat(8, 200px);
  grid-gap: 20px;
  justify-content: center;
  padding: 20px;
  position: relative;
  z-index: 1; /* 确保图片容器的 z-index 低于 Popover */
}

.image-item {
  position: relative;
}

.image-item img {
  width: 200px;
  height: 200px;
  object-fit: cover;
  z-index: 1; /* 确保图片不会覆盖 Popover */
  transition: transform 0.3s ease, z-index 0s ease;
  transform-origin: center;
}

</style>